package com.ssa.web;

import java.util.concurrent.*;

/**
 * ytx MyTest
 *
 * @author <a href="mailto:chenlsh@ytx.com">陈录顺</a>
 * @since 1.0.0
 */
public class CountTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2;
    private int start;
    private int end;

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //任务如果比较小，就直接计算了
        boolean canCompute = (end - start) <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //分成两个子任务
            int middle = (start + end) / 2;
            CountTask leftTask = new CountTask(start, middle);
            CountTask endTask = new CountTask(middle + 1, end);

            //执行子任务
            leftTask.fork();
            endTask.fork();

            //等待子任务执行完毕，并将结果汇总
            int leftTaskResult = leftTask.join();
            int rightTaskResult = endTask.join();
            sum = leftTaskResult + rightTaskResult;
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountTask task = new CountTask(1, 4);
        Future<Integer> result = forkJoinPool.submit(task);
        System.out.println(result.get());

        ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();
        concurrentHashMap.put("", "");
    }
}
